import {ProColumns, ProTable} from '@ant-design/pro-components';
import {message, Modal} from 'antd';
import React, {PropsWithChildren} from 'react';
import {updateGoods} from "@/services/Admin/goodsManage";
import {GOODSNAME_UPDATE} from "@/utils/content";

interface UpdateModalProps {
  oldData: Admin.GoodsResult;
  modalVisible: boolean;
  onSubmit: () => void;
  onCancel: () => void;
}

/**
 * 更新数据模态框
 * @param record
 */
const handleUpdate = async (record: Admin.GoodsResult,oldData:Admin.GoodsResult) => {
  const hide = message.loading('正在配置');
  try {
    let params={
      id:record.id,
      goodsName:record.goodsName,
      typeName:record.typeName,
      price:record.price,
      goodsDescription:record.goodsDescription,
      goodsStatus:record.goodsStatus,
      username:record.username,
      updateEnum:''
    }
    if(record.goodsName!=oldData.goodsName){
      params.updateEnum=GOODSNAME_UPDATE;
    }
    await updateGoods(params);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

/**
 * 更新数据模态框
 * @param props
 * @constructor
 */
const UpdateModal: React.FC<PropsWithChildren<UpdateModalProps>> = (props) => {
  const { oldData,modalVisible, onSubmit, onCancel } = props;
  /**
   * 表格列配置
   */
  const columns: ProColumns<Admin.GoodsResult>[] = [
    {
      dataIndex: 'id',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
    },
    {
      title: '价格',
      dataIndex: 'price',
      search: false,
    },
    {
      title: '商品类型',
      dataIndex: 'typeName',
      search: false,
    },
    {
      title: '商品状态',
      dataIndex: 'goodsStatus',
      valueType: 'select',
      valueEnum: {
        0: {
          text: '下架',
        },
        1: {
          text: '启用',
        },
        2: {
          text: '出售',
        }
      }
    },
  ];
  return (
    <Modal
      destroyOnClose
      title={'更新'}
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={null}
    >
      <ProTable<Admin.GoodsResult, Admin.GoodsResult>
        rowKey="id"
        type="form"
        columns={columns}
        form={{
          initialValues: oldData,
        }}
        onSubmit={async (values) => {
          const success = await handleUpdate({
            ...values,
            id: oldData.id,
          },oldData);
          if (success) {
            onSubmit?.();
          }
        }}
      />
    </Modal>
  );
};

export default UpdateModal;
